package com.cars.elasticsearch.rabbitMQ.consumer;

import com.alibaba.fastjson2.JSON;
import com.cars.elasticsearch.Variable.GlobalVariables;
import com.cars.elasticsearch.domain.DO.Course;
import com.cars.elasticsearch.util.elasticSearch.DocumentUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: caoqianfan
 * @date: 2023/10/12 15:28
 */
@Slf4j
@Component
public class CourseMQListener {

    public static final String QUEUE_COURSE_SAVE = "queue.course.save";
    public static final String QUEUE_COURSE_UPDATE = "queue.course.update";
    public static final String QUEUE_COURSE_REMOVE = "queue.course.remove";
    public static final String KEY_COURSE_SAVE = "key.course.save";
    public static final String KEY_COURSE_UPDATE = "key.course.update";
    public static final String KEY_COURSE_REMOVE = "key.course.remove";
    public static final String COURSE_EXCHANGE = "course.exchange";

    @Resource
    private DocumentUtil documentUtil;

    /**
     * 监听课程添加操作
     */
    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = QUEUE_COURSE_SAVE, durable = "true"),
                    exchange = @Exchange(value = COURSE_EXCHANGE,
                            type = ExchangeTypes.TOPIC,
                            ignoreDeclarationExceptions = "true")
                    , key = KEY_COURSE_SAVE)})
    public void receiveCourseSaveMessage(String message) {
        try {
            log.info("课程添加：{}", message);
            List<Course> courseList = JSON.parseArray(message, Course.class);
            //将消息转为课程，保存到es中
            documentUtil.batchAddDocument(courseList, GlobalVariables.INDEX_NAME_COURSE);
            log.info("添加完成：{}", courseList);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("[ES]课程新增异常,异常信息为:" + e.getMessage());
        }
    }

    /**
     * 监听课程删除操作
     */
    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = QUEUE_COURSE_REMOVE, durable = "true"),
                    exchange = @Exchange(value = COURSE_EXCHANGE,
                            type = ExchangeTypes.TOPIC,
                            ignoreDeclarationExceptions = "true")
                    , key = KEY_COURSE_REMOVE)})
    public void receiveCourseDeleteMessage(List<Long> idList) {
        try {
            List<Course> courseList = new ArrayList<>();
            for (Long id : idList) {
                Course course = new Course();
                course.setId(id);
                courseList.add(course);
            }
            documentUtil.batchDeleteDocument(courseList, GlobalVariables.INDEX_NAME_COURSE);
            log.info("id为{}的课程删除完成!", idList);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("[ES]课程删除异常,异常信息为:" + e.getMessage());
        }
    }

    /**
     * 监听课程修改操作
     */
    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = QUEUE_COURSE_UPDATE, durable = "true"),
                    exchange = @Exchange(value = COURSE_EXCHANGE,
                            type = ExchangeTypes.TOPIC,
                            ignoreDeclarationExceptions = "true")
                    , key = KEY_COURSE_UPDATE)})
    public void receiveCourseUpdateMessage(String message) {
        try {
            log.info("课程更新：{}", message);
            List<Course> courseList = JSON.parseArray(message, Course.class);
            //将消息转为课程，保存到es中
            documentUtil.batchUpdateDocument(courseList, GlobalVariables.INDEX_NAME_COURSE);
            log.info("[ES]课程更新完成：{}", courseList);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("[ES]课程更新异常,异常信息为:" + e.getMessage());
        }
    }
}